package com.simple.shiro;

import java.util.List;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

import org.apache.commons.codec.binary.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.UnauthenticatedException;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.PathMatchingFilter;
import org.apache.shiro.web.util.WebUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import com.simple.entity.SysMenu;
import com.simple.entity.SysUser;
import com.simple.service.SysMenuService;
import com.simple.service.SysRoleService;
import com.simple.utils.SpringUtils;

/**
 * 路径过滤
 * 控制访问权限链接
 */
public class CustomPathMatchingFilter extends PathMatchingFilter{
	
	private static final Logger logger = LoggerFactory.getLogger(CustomPathMatchingFilter.class);

	@Autowired
	SysMenuService sysMenuService;
	
	@Autowired
	SysRoleService sysRoleService;

	@Override
	protected boolean onPreHandle(ServletRequest request, ServletResponse response, Object mappedValue)
			throws Exception {
		String requestUrl=getPathWithinApplication(request);
		Subject subject=SecurityUtils.getSubject();
		if (!subject.isAuthenticated()){
			WebUtils.issueRedirect(request, response, "/login.html");
            return  false;
        }
		if(null==sysMenuService) {
			sysMenuService=SpringUtils.getBean(SysMenuService.class);
		}
		if(null==sysRoleService) {
			sysRoleService=SpringUtils.getBean(SysRoleService.class);
		}
		logger.info("PathMatchingFilter---------------requestUrl"+requestUrl);
		logger.info("PathMatchingFilter---------------subject[{}]"+subject.getPrincipal().toString());
		SysUser sysUser=(SysUser) subject.getPrincipal();
		String ids=sysRoleService.findMenuByUserName(sysUser.getUsername());
		if(org.apache.commons.lang.StringUtils.isNotBlank(ids)) {
			List<SysMenu> sysMenuList=sysMenuService.findByMenuIds(ids.split(","));
			boolean hasPermission =false;
			for (SysMenu sysMenu : sysMenuList) {
				if(sysMenu.getMenuAddress().equals(requestUrl)) {
					hasPermission=true;
					break;
				}
			}
			if(hasPermission) {
				return true;
			}else {
				UnauthenticatedException ue=new UnauthenticatedException("无权限");
				subject.getSession().setAttribute("ue", ue);
				WebUtils.issueRedirect(request, response, "/user/unAuthorized.html");
				return false;
			}
		}else {
			WebUtils.issueRedirect(request, response, "/user/unAuthorized.html");
			return false;
		}
		
		
	}

	
}
